//
//  CameraDetailController.m
//  Runone
//
//  Created by runone02 on 16/11/2.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "CameraDetailController.h"
#import "CameraDetailHeaderView.h"
#import "UIView+Addition.h"
#import "MJRefresh.h"
#import "MJExtension.h"
#import "RequestHelper.h"
#import "DeviceSettingInfoModel.h"
#import "CameraGunDetailListCell.h"
#import "AppDelegate.h"
#import "EnlargeMapViewController.h"
#import "OneConst.h"
#import "HighwayMergeInfoModel.h"
#import "DeviceBaseInfo.h"
#import "UIImageView+WebCache.h"
#import "SDWebImageDownloader.h"
#import "Define.h"
#import "AppLocalManager.h"

#import "SVProgressHUD.h"

@interface CameraDetailController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) CameraDetailHeaderView *cameraDHeaderV;//顶部

@property (nonatomic, strong) DeviceSettingInfoModel *deviceInfo;
@property (nonatomic, strong) NSMutableArray *dataArray;//装图片的数组

@property (nonatomic, assign) NSInteger recordIndex;

@property (nonatomic, strong)  NSMutableArray *allCameraArray;

@property (nonatomic, strong) NSMutableArray *upCameraArray;
@property (nonatomic, strong) NSMutableArray *downCameraArray;
// **************************** -上下切换- ******************************
//@property (nonatomic, strong) DeviceBaseInfo *lastModel;
//@property (nonatomic, strong) DeviceBaseInfo *nextModel;
@end

@implementation CameraDetailController

#pragma mark - 按钮点击
- (void)lastBtnClick {
    _recordIndex -= 1;
    [self getLastAndNextModel];
    [self fetchNewServer];
}

- (void) nextBtnClick {
    _recordIndex += 1;
    [self getLastAndNextModel];
    [self fetchNewServer];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setArray];
    [self configNavigationbar];
    
    if (_fromStationName) {
        [self configHeader];
        [self configTableView];
        
    }else {
        [self gerAllTheDirectionCameraArray];
        [self judgeCameraModelPositionOnArray];
        // 头部
        [self configHeader];
        [self configTableView];
        [self getLastAndNextModel];//模型
    }
}

- (void) setArray {
    _dataArray      = [[NSMutableArray alloc] init];
    _allCameraArray = [[NSMutableArray alloc] init];
}

- (void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = NO;
}
#pragma mark -获取对应方向所有的摄像枪
- (void) gerAllTheDirectionCameraArray {
    
    if (_roadType == RoadTypeUp) {
        for (HighwayMergeInfoModel *mergeInfoModel in _currentRoadModel.mergeInfoList) {
            [self getAllWantCamera:mergeInfoModel.UpWayDevices andDirection:DirectionTypeUp];
        }
    }
    
    if (_roadType == RoadTypeDown) {
        for (HighwayMergeInfoModel *mergeInfoModel in _currentRoadModel.mergeInfoList) {
            [self getAllWantCamera:mergeInfoModel.DownWayDevices andDirection:DirectionTypeDown];
        }
    }
    
    AppDelegate *myDelegate  = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (_roadType == RoadTypeUpAndDown) {
        for (DeviceBaseInfo *moel in myDelegate.AllDeviceBaseArray) {
            if (moel.DeviceType == DevicesTypeCamera && [moel.RoadUID isEqualToString:_currentRoadModel.RoadUID]) {
                [_allCameraArray addObject:moel];
            }
        }
    }
}

- (void)getAllWantCamera:(NSArray *)array andDirection:(DirectionType)type {
    for (DeviceBaseInfo *model in array) {
        if ((model.DeviceType == 4 && model.Direction == type) || (model.DeviceType == 4 && model.Direction == DirectionTypeUPAndDown)) {
            [_allCameraArray addObject:model];
        }
    }
}
#pragma mark- 判断当前摄像枪在方向的位置
- (void) judgeCameraModelPositionOnArray {
    for (int i = 0; i < _allCameraArray.count; i++) {
        DeviceBaseInfo *model = _allCameraArray[i];
        if ([_deviceBaseInfo.DeviceUID isEqualToString:model.DeviceUID]) {
            _recordIndex = i;
            break;
        }
    }
}
#pragma mark -设置上下模型 刷新头部视图的内容
- (void) getLastAndNextModel {
    if (_recordIndex == 0) {
        DeviceBaseInfo *nextModel = _allCameraArray[_recordIndex + 1];
        _deviceBaseInfo           = _allCameraArray[_recordIndex];
        [_cameraDHeaderV setNewData:_deviceBaseInfo LastBtnTitle:nil NextBtnTitle:nextModel Model:_currentRoadModel];
    }else if (_recordIndex == _allCameraArray.count -1) {
        DeviceBaseInfo *laseModel = _allCameraArray[_recordIndex - 1];
        _deviceBaseInfo           = _allCameraArray[_recordIndex];
        [_cameraDHeaderV setNewData:_deviceBaseInfo LastBtnTitle:laseModel NextBtnTitle:nil Model:_currentRoadModel];
    }else {
        DeviceBaseInfo *laseModel = _allCameraArray[_recordIndex - 1];
        DeviceBaseInfo *nextModel = _allCameraArray[_recordIndex + 1];
        _deviceBaseInfo           = _allCameraArray[_recordIndex];
        [_cameraDHeaderV setNewData:_deviceBaseInfo LastBtnTitle:laseModel NextBtnTitle:nextModel Model:_currentRoadModel];
    }
}

- (void) configHeader { // mark:_tagFromStation
    _cameraDHeaderV            = [[CameraDetailHeaderView alloc] init];
    _cameraDHeaderV.fromStationName   = _fromStationName;
    _cameraDHeaderV.frame      = CGRectMake(0, 0, self.view.bounds.size.width, 260);
    [_cameraDHeaderV.enlargeBtn addTarget:self action:@selector(enlargeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_cameraDHeaderV.lastBtn addTarget:self action:@selector(lastBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_cameraDHeaderV.nextBtn addTarget:self action:@selector(nextBtnClick) forControlEvents:UIControlEventTouchUpInside ];
    
    [_cameraDHeaderV setNewData:_deviceBaseInfo LastBtnTitle:nil NextBtnTitle:nil Model:_currentRoadModel];
}

#pragma mark - 放大地图
- (void) enlargeBtnClick {
    EnlargeMapViewController *vc = [[EnlargeMapViewController alloc] init];
    vc.la   = _deviceBaseInfo.Latitude;
    vc.lo   = _deviceBaseInfo.Longitude;
    vc.type = AllIconTypeCamera;
    [self presentViewController:vc animated:YES completion:nil];
}

- (void) configNavigationbar {
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
    UILabel *titleLabel  = [[UILabel alloc] init];
    titleLabel.size      = CGSizeMake(100, 30);
    titleLabel.text      = @"摄像枪详情";
    titleLabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titleLabel;
}

- (void) configTableView {
    _tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height - 64) style:UITableViewStylePlain];
    [_tableview registerNib:[UINib nibWithNibName:@"CameraGunDetailListCell" bundle:nil] forCellReuseIdentifier:@"CameraGunDetailListCell"];
    _tableview.delegate       = self;
    _tableview.dataSource     = self;
    _tableview.rowHeight      = 250;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableview.contentInset   = UIEdgeInsetsMake(0, 0, 49, 0);
    _tableview.tableHeaderView = _cameraDHeaderV;
    [self.view addSubview:_tableview];
    
    _tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [self fetchNewServer];
    [self.tableview reloadData];
}
-(void)loadNewData {
    [_dataArray removeAllObjects];
    [self fetchNewServer];
    [_tableview.mj_header endRefreshing];
}

- (void) fetchNewServer {
    [_dataArray removeAllObjects];
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *getCurrentEventModel = [[RequestGinsengModel alloc] init];
    getCurrentEventModel.URL                  = GetDeviceDataURL;
    getCurrentEventModel.DataValue            = [self DataValueStr:_deviceBaseInfo.DeviceUID];
    getCurrentEventModel.UpdatedTime          = @"";
    getCurrentEventModel.SystemCode           = @"GuangleHighway";
    getCurrentEventModel.MethodName           = @"GetDeviceSettingInfo";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        //        NSLog(@"%@",requestOutginseng);
        if ([requestOutginseng.Code isEqualToString:@"001"]) {
            _deviceInfo =[DeviceSettingInfoModel mj_objectWithKeyValues:requestOutginseng.DataValue];
            NSLog(@"%@",_deviceInfo.DeviceData.VideoPictures);
            [_dataArray addObjectsFromArray:_deviceInfo.DeviceData.VideoPictures];
            [self.tableview reloadData];
        }
    };
    [requestHelper RequestGinsengModel:getCurrentEventModel andPushController:self];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *str=@"Bearer ";
    NSString *strone;
    
    CameraGunDetailListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CameraGunDetailListCell"];
    cell.selectionStyle           = UITableViewCellSelectionStyleNone;
    NSString *img=_dataArray[indexPath.row];
    NSString *timeLab=[img substringFromIndex:img.length-21];
    [cell timeLabelString:timeLab];
    SDWebImageDownloader *sdmanager = [SDWebImageManager sharedManager].imageDownloader;
    
    if (GETACCESS_TOKEN!=nil) {
        NSLog(@"%@",GETACCESS_TOKEN);
        strone=[str stringByAppendingString:GETACCESS_TOKEN];
        [sdmanager setValue:strone forHTTPHeaderField:@"Authorization"];
    }
    //http://183.61.31.2:8060/api/DownloadCameraImage?cameraUID=ae874469-a480-4786-8da8-0396b54db41e&imgName=20170311135841592.jpg
    [cell.cameraImage sd_setImageWithURL:[img mj_url]];
    
//    [cell setCellData:_dataArray[indexPath.row]];
    return cell;
}


#pragma mark - 拼接参数
-(NSString *)DataValueStr:(NSString *)str{
    NSString *minStr   = @"120";
    NSString *indexStr = @"1,2,3,5,10,15,30,45,60,120";
    NSString *beginstr=[NSString stringWithFormat:@"[{\"key\":\"DeviceUID\",\"value\":\"%@\"},{\"key\":\"Minutes\",\"value\":\"%@\"},{\"key\":\"SelectPicIndex\",\"value\":\"%@\"}]",str,minStr,indexStr];
    
    return beginstr;
}


@end
